package com.jinly.ryder.ssh.command;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;
import com.jinly.ryder.common.error.SystemErrorType;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CommonCommand {
    private Session sshSession;

    public CommonCommand(Session sshSession) {
        this.sshSession = sshSession;
    }

    public List<String> exec(String command) {
        log.info("command:{}", command);
        ChannelExec channelExec = null;
        BufferedReader reader = null;
        List<String> result = new ArrayList<>();
        try {
            channelExec = (ChannelExec) sshSession.openChannel("exec");
            channelExec.setCommand(command);
            channelExec.connect(60 * 1000);
            reader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                log.info("exec:{}", line);
                result.add(line);
            }
        } catch (Exception e) {
            log.error("ssh {}  err:{}", command, e.getMessage());
            SystemErrorType.INTERNAL_SERVER_ERROR.throwError("ssh命令执行失败");
        } finally {
            try {
                if (reader != null) reader.close();
                if (channelExec != null) channelExec.disconnect();
            } catch (Exception e) {
            }
        }
        return result;
    }

}

